const request = require('request')
// var NodeCache = require('node-cache') ;
var wxconfig = require('../appConfig').wxconfig;
var getAccessTokenUrl = wxconfig.accessTokenUrl;
// var myCache = new NodeCache({  stdTTL :3600 ,  checkperiod :3600 });

var getAccessToken = function(code) {
    return new Promise(function (resolve, reject) {
        // var tempToken = myCache.get( "ACCESS_TOKEN_INFO" );
        // if(tempToken){
        //     resolve(tempToken)
        // }else {
            request.get({
                uri: getAccessTokenUrl,
                json: true,
                qs: {
                    grant_type: 'authorization_code',
                    appid: wxconfig.appid,    // APPID请换成你的 appid
                    secret: wxconfig.secret,    // APPSECRET请换成你的 appsecret
                    code:code
                }
            }, (err, res, body) => {
                if (err) {
                    reject(err)
                }
                // err exp : {"errcode":40003,"errmsg":" invalid code "}
                if (body.errcode) {
                    reject(body.errcode + body.errmsg)
                 }
                resolve(body)
            // myCache.set('ACCESS_TOKEN_INFO',body,function(err,success){
            //     if( !err && success ){
            //         var  tempvalue = myCache.get( "ACCESS_TOKEN_INFO" );
            //         resolve(tempvalue)
            //     }
            // })
        })
        // }
    })
}
// 只要向外暴露一个获取值的方法就可以了
module.exports = getAccessToken
